<?php
/**
 * Created by PhpStorm.
 * User: Lenovo
 * Date: 2018/12/5
 * Time: 10:30
 */

namespace app\manage\controller;


use app\manage\model\Agency;
use app\manage\model\Draw;
use app\manage\model\Indent;
use app\manage\model\User;
use think\Request;
use think\Session;

class Draws extends Comm
{
    public function index(){
        $Tid=Session::get('userid');
        $re=Draw::getRoyaltys();
        $agent=Agency::getagents($Tid);
        $indent=Indent::getIndentsnum($Tid);
        $yuer=User::get($Tid)->money;
        $drawmoney=User::get($Tid)->draw;
        return view('index',['agent'=>$agent,'indent'=>$indent,'draw'=>$re,'yuer'=>$yuer,'drawmoney'=>$drawmoney,'i'=>1]);
    }
    public function add(){
        $Tid=Session::get('userid');
        $yuer=User::get($Tid)->money;
        return view('add',['yuer'=>$yuer]);
    }
    public function checkadd(){
        $request=Request::instance();
        $data=$request->post();
        $Tid=Session::get('userid');
        $yuer=User::get($Tid)->money;
        $re=(new \app\manage\validate\Draw())->goCheck();
        if($re===true){
            if($data['money']<=$yuer){
                try{
                    Draw::startTrans();
                    $re=Draw::addRoyalty($data);
                    $res=User::get($Tid);
                    $res->money=($res->money)-$data['money'];
                    $res->save();
                    Draw::commit();
                    if($re){
                        $this->success('申请成功,等待审核','manage/draws/index');
                    }else{
                        $this->error('申请失败','manage/draws/add');
                    }
                }catch (Exception $exception){
                    Draw::rollback();
                    $this->error('申请失败','manage/draws/add');
                }
            }else{
                $this->error('申请金额大于余额','manage/draws/add');
            }
        }else{
            $this->error($re,'manage/draws/add');
        }
    }
}